#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int voltage = 0;
int cvoltage = 0;
int set_voltage = 0;
void setup() {
  // set up the LCD's number of columns and rows: 
    pinMode(9, OUTPUT);            // set discharge pin to output 
    pinMode(8, INPUT);            // set charge pin to input (high impedance)
    pinMode(7, INPUT); 
    pinMode(10, INPUT);
    digitalWrite(7, HIGH); 
    digitalWrite(10, HIGH);  
    //attachInterrupt(0, interrupttrigger, LOW); //Interrupt 0 is Digital Pin 2


  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Charge Counter");
  lcd.setCursor(0,1);
  lcd.print("Designed for RPI");
  delay(2000);
  disp_units();
  
  
}

void disp_units(){
  lcd.setCursor(0,1);
  lcd.print("     V      - uC");
}

void charge(){
   pinMode(8, OUTPUT); 
   digitalWrite(8,OUTPUT);
   digitalWrite(9,HIGH);
   delay(50);
   lcd.setCursor(0,0);
   lcd.print("Cap. Charged    ");
   set_voltage = analogRead(0);
 
   
}

int measure(){
   cvoltage = 0;
   int counter = 0;
   pinMode(8, OUTPUT); 
   digitalWrite(8,OUTPUT);
   digitalWrite(9,HIGH);
   delay(10);
   
   cvoltage = analogRead(1);
   unsigned long time;
   pinMode(8, INPUT);  
   time = micros();
   digitalWrite(9,LOW);

    
    
   while (cvoltage>376 && counter<100000){
     cvoltage = analogRead(1);
     counter++;
   }
   if (counter == 10000){
     lcd.setCursor(0,1);
     lcd.print("Error charging! ");
     delay(5000);
   }
   else {
     unsigned long etime;
     etime = micros() - time - 232;
     

     lcd.setCursor(9,1);
   //  lcd.print(((float)etime/2000000.0) , 5);
     lcd.print(((float)etime/200000.0)*voltage/1000,3);
   }
   
   while(digitalRead(10)){
     lcd.setCursor(0,0);
    lcd.print("Press 'Charge'  ");    
  }
   disp_units();
   return time;
}

void loop() {
  cvoltage = analogRead(1);
  voltage = analogRead(0);    // read the input pin  
  if (voltage < 1000){
    lcd.setCursor(4, 1);
    lcd.print(" ");
  }
  lcd.setCursor(0, 1);
  lcd.print((double)voltage/100,2);
  if (cvoltage < 1020 || (set_voltage-voltage)>3 || (set_voltage-voltage)<-3){
      lcd.setCursor(0,0);
      lcd.print("Cap. Not Charged");
  }
  if (digitalRead(10)==LOW){
    charge();  
  }
  if (digitalRead(7)==LOW){
    measure();
  }
  
  // (note: line 1 is the second row, since counting begins with 0):
  //lcd.setCursor(7, 1);
  // print the number of seconds since reset:
  //lcd.print(millis()/1000);
}

